<!-- EffectScope 作用域演示 -->
<script setup>
import { computed, watch, watchEffect, effectScope, ref } from "vue";

let nestedScope;
let counter, doubled;

// 创建父作用域
const parentScope = effectScope();

parentScope.run(() => {
  counter = ref(0);
  doubled = computed(() => counter.value * 2);

  // 嵌套作用域（detached=true 表示独立，不受父作用域 stop() 影响）
  nestedScope = effectScope(true);
  nestedScope.run(() => {
    watch(doubled, () => {
      console.log("%c[嵌套作用域] doubled: " + doubled.value, "color: #1abc9c");
    });
  });

  // 父作用域中的 watchEffect
  watchEffect(() => {
    console.log("%c[父作用域] Count: " + doubled.value, "color: #e67e22");
  });
});

// 停止父作用域（不会影响 detached 的嵌套作用域）
const stopParent = () => {
  console.log("%c停止父作用域", "color: red; font-weight: bold;");
  parentScope.stop();
};

// 停止嵌套作用域
const stopNested = () => {
  console.log("%c停止嵌套作用域", "color: blue; font-weight: bold;");
  nestedScope.stop();
};
</script>

<template>
  <div style="padding: 20px">
    <h3>effectScope 演示</h3>
    <p>Count: {{ counter }} | Doubled: {{ doubled }}</p>

    <button @click="counter++">增加</button>
    <button @click="stopParent">停止父作用域</button>
    <button @click="stopNested">停止嵌套作用域</button>

    <p style="color: #666; font-size: 14px; margin-top: 10px">
      打开控制台查看 effectScope 的日志输出。
    </p>
  </div>
</template>

<style scoped>
button {
  margin-right: 8px;
  padding: 6px 12px;
  border-radius: 6px;
  border: 1px solid #ccc;
  cursor: pointer;
}
</style>
